package cn.winwintech.screenlocker

import android.app.NotificationManager
import android.app.PendingIntent
import android.app.admin.DevicePolicyManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit

/**
 * Top-level function handling relock logic after device unlock/reboot
 * @param context Context used for system services and preferences
 */
fun lock(context: Context) {
    val sharedPreferences =
        context.getSharedPreferences(Constants.APP_PREF, Context.MODE_PRIVATE)
    val lockTime = sharedPreferences.getLong(Constants.LOCK_TIME, 0)
    val unlocking = sharedPreferences.getBoolean(Constants.UNLOCKING, false)
    val lockStartTime = sharedPreferences.getLong(Constants.LOCK_START_TIME, 0)
    if (System.currentTimeMillis() < lockTime && !unlocking && System.currentTimeMillis() > lockStartTime) {
        val allowUnlock = sharedPreferences.getBoolean(Constants.ALLOW_UNLOCK, true)
        // 提醒用户
        val activityIntent = Intent(context, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder = NotificationCompat.Builder(context, "keep_alive_channel")
            .setSmallIcon(R.drawable.notificaiton_icon)
            .setContentTitle("锁屏提醒")
            .setContentText("锁屏时间未到，设备将再次锁屏")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
        if(allowUnlock){
            builder.setContentIntent(pendingIntent)
                .setContentTitle("解锁提醒")
                .setContentText("锁屏时间未到，设备将再次锁屏，请在10秒内解锁屏幕")
        }
        notificationManager.notify(2, builder.build())
        if(allowUnlock){
            // 重新调度任务
            val workManager = WorkManager.getInstance(context)
            workManager.enqueue(
                OneTimeWorkRequest.Builder(LockScreenWorker::class.java)
                    .setInitialDelay(10, TimeUnit.SECONDS) // 10秒后再次执行
                    .build()
            )
        } else {
            // 再次锁屏
            val devicePolicyManager =
                context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
            devicePolicyManager.lockNow()
        }

    }
}

/**
 * Broadcast receiver handling device reboot events
 * Ensures screen lock persists across device restarts
 */
class RebootReceiver : BroadcastReceiver() {
    /**
     * Trigger lock check after system boot completes
     */
    override fun onReceive(context: Context, intent: Intent) {
        if (Intent.ACTION_BOOT_COMPLETED == intent.action ) {
            lock(context)
        }
    }
}

/**
 * Broadcast receiver handling device unlock events
 * Listens for user-present intent to check lock status
 */
class UnlockReceiver : BroadcastReceiver() {
    /**
     * Trigger lock check when user unlocks device
     */
    override fun onReceive(context: Context, intent: Intent) {
        if (Intent.ACTION_USER_PRESENT == intent.action) {
            lock(context)
        }
    }
}